﻿using Android.Graphics;
using Android.Net;
using cn.tozhang.linksms.data.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace cn.tozhang.linksms
{
    internal static class SmsManager
    {
        /**
         * 所有的短信
         */
        public const string SMS_URI_ALL = "content://sms/";
        /**
         * 收件箱短信
         */
        public const string SMS_URI_INBOX = "content://sms/inbox";
        /**
         * 发件箱短信
         */
        public const string SMS_URI_SEND = "content://sms/sent";
        /**
         * 草稿箱短信
         */
        public const string SMS_URI_DRAFT = "content://sms/draft";



        internal static IEnumerable<SmsInfo> ReadSMS_MSG()
        {
            string[] projection = ["_id", "address", "person", "body", "date", "type"];
            if (Application.Context.ContentResolver == null) goto END_ReadSMS_MSG;
            var uri = Android.Net.Uri.Parse(SMS_URI_INBOX);
            if (uri == null) goto END_ReadSMS_MSG;

            var cusor = Application.Context.ContentResolver.Query(uri, projection, null, null, "date desc");
            if (cusor == null) goto END_ReadSMS_MSG;

            int nameColumn = cusor.GetColumnIndex("person");
            int phoneNumberColumn = cusor.GetColumnIndex("address");
            int smsbodyColumn = cusor.GetColumnIndex("body");
            int dateColumn = cusor.GetColumnIndex("date");
            int typeColumn = cusor.GetColumnIndex("type");

            if (cusor != null)
            {
                if (cusor.MoveToFirst())
                do
                {
                    SmsInfo smsinfo = new SmsInfo();
                    smsinfo.setName(cusor.GetString(nameColumn) ?? string.Empty);
                    smsinfo.setDate(cusor.GetString(dateColumn) ?? string.Empty);
                    smsinfo.setPhoneNumber(cusor.GetString(phoneNumberColumn) ?? string.Empty);
                    smsinfo.setSmsbody(cusor.GetString(smsbodyColumn) ?? string.Empty);
                    smsinfo.setType(cusor.GetString(typeColumn) ?? string.Empty);
                    yield return smsinfo;
                }
                while (cusor.MoveToNext());
                cusor.Close();
            }

        END_ReadSMS_MSG:

            ;
        }
    }
}
